package com.demo.spring.cloud.gateway.config;

import com.demo.spring.cloud.gateway.filter.ElapsedGatewayFilterFactory;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import reactor.core.publisher.Mono;

/**
 * @author wangzhilong
 * @date 2019-06-14
 */
@Configuration
public class GatewayConfig {


    @Bean
    public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
        return builder.routes()
                .route("path_route", r -> r.path("/about").uri("http://ityouknow.com"))
//                .route("elapsed_time_route", r -> r.path("/**")
//                        .filters(f -> f.filter(new ElapsedTimeFilter()).addResponseHeader("X-Response-Default-Foo", "Default-Bar"))
//                        .uri("lb://SPRING-CLOUD-PRODUCER"))
                .build();
    }

    /**
     * 创建局部过滤器工厂Bean
     * @return
     */
    @Bean
    public ElapsedGatewayFilterFactory gatewayFilterFactory(){
        return new ElapsedGatewayFilterFactory();
    }

    /**
     * 根据请求参数中的 user 字段来限流
     * @return
     */
    @Bean
    public KeyResolver userKeyResolver(){
        return exchange -> Mono.just(exchange.getRequest().getQueryParams().getFirst("user"));
    }

    /**
     * 设置根据请求 IP 地址来限流
     * @return
     */
    /*@Bean
    public KeyResolver ipKeyResolver(){
        return exchange -> Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
    }*/




}
